const webpack = require('webpack');
const webpackProdConfig = require('./webpack.config.prod');
const fs = require('fs');
const path = require('path');

// remove dist directory
fs.rmSync(path.join(__dirname, 'dist'), { recursive: true, force: true });

function removeMapFiles(dir) {
  const children = fs.readdirSync(dir, { withFileTypes: true });
  children.forEach((entry) => {
    if (entry.isDirectory()) {
      removeMapFiles(path.join(dir, entry.name));
    } else if (/\.(js|css)\.map/.test(entry.name)) {
      fs.unlinkSync(path.join(dir, entry.name));
    }
  });
}

// run webpack build
webpack(webpackProdConfig, (err, stats) => {
  if (err) {
    console.error(err.stack || err);
    if (err.details) {
      console.error(err.details);
    }
    return;
  }

  // const info = stats.toJson();

  // if (stats.hasErrors()) {
  //   console.error(info.errors);
  // }

  // if (stats.hasWarnings()) {
  //   console.warn(info.warnings);
  // }

  console.log(
    stats.toString({
      chunks: true, // Makes the build much quieter
      colors: true, // Shows colors in the console
    })
  );

  removeMapFiles(path.join(__dirname, 'dist'));
});